package Report.XML;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.*;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
//import org.apache.crimson.tree.XmlDocument;
import org.apache.xml.serialize.XMLSerializer;

public class ManipulaXML {
    //Metodos
    public void modificaXML (String relatorioNome,String novaQuery) throws ParserConfigurationException, SAXException, IOException{
       String arquivojrxml = relatorioNome+".jrxml";
       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
       DocumentBuilder db = dbf.newDocumentBuilder();

       Document doc = (Document) db.parse(arquivojrxml);
       Element raiz = doc.getDocumentElement();
       NodeList test = raiz.getChildNodes();
       //Testa se a tag queryString existe (a escruindo se ela existir)
       if (test.item(1).getNodeName().equals("queryString")){
           NodeList queryNew = raiz.getElementsByTagName("queryString");
           raiz.removeChild(queryNew.item(0));
       }
       //Criando o elemento queryString antes do primeiro field
       NodeList field = raiz.getElementsByTagName("field");
       raiz.insertBefore(doc.createElement("queryString"), field.item(0));
       //Definindo a linguagem da tag queryString para sql
       Attr sql = doc.createAttribute("language");
       sql.setValue("SQL");
       NodeList query = raiz.getElementsByTagName("queryString");
       Element queryTag = (Element) query.item(0);
       queryTag.setAttributeNode(sql);
       //Criando uma tag CDATA na String query
       queryTag.appendChild(doc.createCDATASection(novaQuery));
       //Salvando as alteracoes no arquivo XML
       //XmlDocument xmlDoc = (XmlDocument) doc;
       //xmlDoc.write(new FileOutputStream(arquivojrxml));
       //System.out.println("XML modificado com sucesso");

          XMLSerializer serializer = new XMLSerializer();
          serializer.setOutputCharStream(
          new java.io.FileWriter(arquivojrxml));
          serializer.serialize(doc);

    }
}
